(async function() {

    var manifestJsonStr = ''
    var registerContentScripts = () => {
        chrome.scripting.getRegisteredContentScripts(rcs => {
            console.log(rcs);
        });
    };
    var script = function() {
      alert("Hi!");
    };

    var execScript = function(tabId, script) {
        chrome.scripting.executeScript({
            target: { tabId: tabId },
            func: script,
        });
    };

    var currentTab = new Promise((resolve, reject) => {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            var currentTab = tabs[0];
            if (currentTab) {
                resolve(currentTab);
            } else {
                reject("false");
            }
        });
    });

    var plugins = {
        initialized: false,
        _pluginInterfaces: [],
        _plugins: [],
        _manifests: [],
        exec: async function() {
            if(!plugins.initialized) {
                console.log("Waiting for initialization");
                setTimeout(plugins.exec, 1);
            } else {

                var checkRule = async (pattern) => {
                    return currentTab().then(tab => {
                        console.log(tab.url);
                        return pattern.test(tab.url);
                    })
                    return pattern.test();
                }
                var execPlugin = ({class_name: cn, matches: matches, js: js}) => {
                    console.log(cn, matches, js);
                    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                        console.log(tabs[0].id);
                        execScript(tabs[0].id, script);
                    });
                }
                plugins._plugins.forEach(execPlugin)
            }
        },

        init: async function() {
            var readFile = async function(file){
                var content = "";
                var url = chrome.runtime.getURL(file);
                try {
                    content = await fetch(url).then(function(response){
                        if(response.ok && response.status === 200){
                            return response.text();
                        } else throw new Error(`status: ${response.status}`);
                    }).catch(function(err){
                        console.log(err);
                        return ""
                    })
                } catch (e) {
                    console.log("getRawContent " + e);
                }
                return content;
            };
            var loadManifest = async function(file){
                return readFile(file)
                        .then(res => JSON.parse(res))
                        .catch((err) => {
                            console.log("loadManifest error", err);
                            return null;
                        });
            }
            var manifest = await loadManifest("assets/plugins/manifest.json");
            plugins._manifests = manifest.manifests;
            plugins._pluginInterfaces.push(...manifest.plugins);
            for(var file of manifest.manifests) {
                await loadManifest(file).then(res => {
                    for(var a in res.plugins) {
                        for(var b in res.plugins[a].js) {
                            res.plugins[a].js[b] = chrome.runtime.getURL(res.plugins[a].js[b]);
                        }
                    }
                    plugins._plugins.push(...res.plugins);
                });
            }
            plugins.initialized = true;
            // console.log(plugins);
        }
    };

    var search = (sender) => {
        console.log(sender);
        var test = function() {
            console.log("isSearching");
        }
        execScript(sender.tab.id, test);
    }

    var installed = function({reason}) {
        console.log(reason);
        checkUpdate();
        if (reason == chrome.runtime.OnInstalledReason.INSTALL) {
            console.info("installed");
        }
        registerContentScripts();
        plugins.init();
    };
    var onMessageListener = function(message, sender, cb) {
        console.log(message, sender, cb);
        switch(message.action) {
            case "getSearchPlugins":
                console.log(plugins._plugins);
                // search(sender);
                cb({
                    tabId: sender.tab.id,
                    plugins: plugins._plugins,
                    pluginInterfaces: plugins._pluginInterfaces
                });
                break;
        }
    }
    chrome.runtime.onInstalled.addListener(installed);
    chrome.action.onClicked.addListener((tab) => {
        console.info("clicked");
        plugins.exec();
    });
    chrome.runtime.onMessage.addListener(onMessageListener);
})();